﻿using EventBus;
using LiteStep.Currencies;
using LiteStep.Events;
using LiteStep.Exchanges;
using LiteStep.Exchanges.MtGox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LiteStep.Conversions.ConversionUpdaters
{
	public class MtGoxTickerConversionUpdater<TFrom, TTo> : BasicTickerConversionUpdater<TFrom, TTo, MtGox, Ticker<TFrom, TTo>>
		where TFrom : ICurrency<TFrom>, new()
		where TTo : ICurrency<TTo>, new()
	{
		public MtGoxTickerConversionUpdater(IConversionManager conversionManager, IEventBus eventBus)
			: base(conversionManager, eventBus)
		{
		}

		public override void OnAfterTickerResponseEvent(AfterTickerResponseEvent<Ticker<TFrom, TTo>> e)
		{
			if (e == null || e.Ticker == null) { return; }
			
			IConversion<TFrom, TTo, MtGox> forward;
			IConversion<TTo, TFrom, MtGox> backward;

			forward = new SimpleConversion<TFrom, TTo, MtGox>(e.Ticker.Buy.ValueInt * ValueIntMultiplier.Get(e.Ticker.Buy.Currency), e.Ticker.Timestamp);
			backward = new SimpleConversion<TTo, TFrom, MtGox>(1.0M / (e.Ticker.Sell.ValueInt * ValueIntMultiplier.Get(e.Ticker.Sell.Currency)), e.Ticker.Timestamp);

			conversionManager.Set<TFrom, TTo, MtGox>(forward);
			conversionManager.Set<TTo, TFrom, MtGox>(backward);

			eventBus.FireEvent(new ConversionUpdatedEvent<TFrom, TTo, MtGox>(forward));
			eventBus.FireEvent(new ConversionUpdatedEvent<TTo, TFrom, MtGox>(backward));
		}
	}
}
